package com.kgcx.order.rabbitmq;

import com.alibaba.fastjson.JSONObject;
import com.kgcx.common.api.ApiContant;
import com.kgcx.common.client.organization.DriverClient;
import com.kgcx.common.client.organization.pojo.Driver;
import com.kgcx.common.client.schedule.pojo.ScheduleRecord;
import com.kgcx.common.eum.OrderEnum;
import com.kgcx.common.rabbitmq.bean.Message;
import com.kgcx.common.rabbitmq.consts.ExchangeConst;
import com.kgcx.common.rabbitmq.consts.RoutingKeyConst;
import com.kgcx.core.utils.JsonUtil;
import com.kgcx.order.common.Util;
import com.kgcx.order.domain.Order;
import com.kgcx.order.domain.Order4Flat;
import com.kgcx.order.entity.OrderChangeMessage;
import com.kgcx.order.service.OrderDriverService;
import com.kgcx.order.service.OrderService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;


/**
 * Created by zhulong on 17/11/13.
 * 派车成功
 */
@Component

public class AutoDispatchSuccessListener {

    private static final Logger LOG = LoggerFactory.getLogger(AutoDispatchSuccessListener.class);
    @Autowired
    private StringRedisTemplate strRedisTemplate;
    //    @Autowired
//    private JsonRedisTemplate<DriverOrderSummary> dosRdsTmp;
    @Autowired
    private OrderDriverService orderDriverService;
    @Autowired
    private DriverClient driverClient;

    @Autowired
    private RabbitTemplate rabbitTemplate;
    @Autowired
    private OrderService service;

    @RabbitListener(queues = "kgcxOrderAutoDispatchSuccessQueue", errorHandler = "custRabbitListenerErrorHandler")
    public void processOrderStatus(String json) {

        LOG.info("订单 - 派车成功，json=" + json);
        //获取并解析消息
        ScheduleRecord schRecord = JsonUtil.toObject(json, ScheduleRecord.class);

        strRedisTemplate.opsForHash()
                .put(OrderEnum.ORDERS_STATUS, schRecord.getOrder_no(),
                        String.valueOf(OrderEnum.AUTO_DISPATCH_SUCESS));

        Order order = service.getIngOrderByOrderNo(schRecord.getOrder_no());

        if (order != null && schRecord != null) {
            order.setModel(schRecord.getAuto_type());
            order.setAutoId(schRecord.getAuto_id());
            order.setAutoNo(schRecord.getAuto_no());
            order.setDriverId(schRecord.getDriver_id());
            order.setDriverName(schRecord.getDriver_name());
            order.setDriverPhone(schRecord.getDriver_phone());
            order.setOrderState(OrderEnum.AUTO_DISPATCH_SUCESS);

            String recordJson = JsonUtil.toString(order);
            strRedisTemplate.opsForHash()
                    .put(OrderEnum.ORDERS_ING, order.getOrderNo(), recordJson);

            //派车成功，给司机一个服务中订单
            String driverKey = Util.getDriverOrdersInServiceKey(order.getDriverId());
//            if(strRedisTemplate.opsForList().size(driverKey) > 0)
//            {
//                LOG.info(String.format("司机已经有服务中订单，不能继续派单，driverKey：{%s}", driverKey));
//            }
//            else
//            {
            strRedisTemplate.opsForList().leftPush(driverKey, order.getOrderNo());
//            }
            //司机订单概览 订单数+1
            //现在改为乘客支付完成或者司机设为代付 接单数才增加
//            orderDriverService.add(schRecord.getDriver_id(), 1,0);

            // 给监管平台发消息
            LOG.info(String.format("派车成功的MQ消息，订单号[%s]。", order.getOrderNo()));

            Driver driver = driverClient.getDriver(order.getDriverId(), null);
            Order4Flat of = new Order4Flat();
            of.setOrder(order);
            if (driver != null) {
                of.setDriverLicenseId(driver.getLicenseId());
            }
            Message msg = Message.buildMessage(ApiContant.ORDER_MATCH, Message.FLAG_ADD, of);
            rabbitTemplate.convertAndSend(ExchangeConst.OPC, RoutingKeyConst.OPC_COMMON, JSONObject.toJSONString(msg));

            //TODO mqtt发给用户端 派车成功
            OrderChangeMessage mqMsg = new OrderChangeMessage(order.getOrderNo()
                    , OrderEnum.AUTO_DISPATCH_SUCESS, OrderChangeMessage.MESSAGE_TYPE_DISPATCH_SUCCESS, "", order.getPlacingUserId());
            service.sendMqtt(JsonUtil.toString(mqMsg)
                    , OrderEnum.ORDER_STATE_TOPIC + "." + order.getPlacingUserId());

        }
    }
}
